package controllers

import (
	"encoding/json"
	"ssims/models"
	"ssims/pkg/app"
	"ssims/pkg/e"
	"ssims/services"

	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

func GetEvent(c *gin.Context) {
	page := -1
	if arg := c.Query("page"); arg != "" {
		page = com.StrTo(arg).MustInt()
	}
	limit := -1
	if arg := c.Query("limit"); arg != "" {
		limit = com.StrTo(arg).MustInt()
	}
	searchId := ""
	if arg := c.Query("searchId"); arg != "" {
		searchId = arg
	}
	supplierParam := map[string]interface{}{
		"page":     page,
		"limit":    limit,
		"searchId": searchId,
	}
	err, info, total := services.GetAllEvent(supplierParam)
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{"value": info, "total": total}, "查询成功")
}

func GetEvent1(c *gin.Context) {
	page := -1
	if arg := c.Query("page"); arg != "" {
		page = com.StrTo(arg).MustInt()
	}
	limit := -1
	if arg := c.Query("limit"); arg != "" {
		limit = com.StrTo(arg).MustInt()
	}
	searchId := ""
	if arg := c.Query("searchId"); arg != "" {
		searchId = arg
	}
	supplierParam := map[string]interface{}{
		"page":     page,
		"limit":    limit,
		"searchId": searchId,
	}
	err, info, total := services.GetAllEvent1(supplierParam)
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{"value": info, "total": total}, "查询成功")
}
func DelEvent(c *gin.Context) {
	id := ""
	if arg := c.Query("family_id"); arg != "" {
		id = arg
	}
	if id == "" {
		app.INFO(c, 30001, "参数错误")
		return
	}
	err := services.DelEvent(id)
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "删除成功")
}

func UpdateEvent(c *gin.Context) {
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	if m["FamilyId"] == "" {
		app.INFO(c, 30000, "参数非法")
		return
	}
	family_id := m["FamilyId"]
	event_time := m["EventTime"]
	event_type := m["EventType"]
	event_des := m["EventDes"]
	event_fj := m["EventFj"]

	err := services.UpdateEvent(models.Event{
		FamilyId:  family_id,
		EventTime: event_time,
		EventType: event_type,
		EventDes:  event_des,
		EventFj:   event_fj,

		Isdel: false})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "更新成功")
}

func AddEvent(c *gin.Context) {
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	family_id := m["FamilyId"]
	event_time := m["EventTime"]
	event_type := m["EventType"]
	event_des := m["EventDes"]
	event_fj := m["EventFj"]

	err := services.AddEvent(models.Event{
		FamilyId:  family_id,
		EventTime: event_time,
		EventType: event_type,
		EventDes:  event_des,
		EventFj:   event_fj,

		Isdel: false})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "添加成功")
}
